package com.song.oa.config;

import com.song.oa.filter.JwtAuthencationTokenFilter;
import com.song.oa.filter.RestAuthorizationEntryPoint;
import com.song.oa.filter.RestfulAccessDeniedHandler;
import com.song.oa.service.impl.LoginUserService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @Author 宋伟宁
 * @Date 2024/3/19
 * @Version 1.0
 **/
@Configuration
//@EnableWebSecurity
public class SecurityConfig {

    //jwt
    @Resource
    private JwtAuthencationTokenFilter jwtAuthencationTokenFilter;
    @Resource
    private RestAuthorizationEntryPoint authorizationEntryPoint;
    @Resource
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Resource
    private LoginUserService loginUserService;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }



    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(resp->
                        resp.requestMatchers("/captcha","/login","/v3/api-docs","/v3/api-docs/**","/swagger-ui.html","/swagger-ui/**").permitAll()
                       .anyRequest().authenticated()
                );
       // http.formLogin(Customizer.withDefaults());
       http.sessionManagement(conf-> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        http.csrf().disable();

        http.addFilterBefore(this.jwtAuthencationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling()
                //授权失败
                .accessDeniedHandler(this.restfulAccessDeniedHandler)
                .authenticationEntryPoint(this.authorizationEntryPoint);
        return  http.build();
    }


}
